<template>
  <el-card>
    <!-- 1.0 标题 -->
    <template #header>账号修改</template>
    <!-- 2.0 内容 -->
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
      size="mini"
    >
      <el-form-item label="旧密码" prop="oldpass">
        <el-input
          type="text"
          v-model="ruleForm.oldpass"
          autocomplete="off"
          @blur="judge"
        ></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="pass">
        <el-input
          type="password"
          v-model="ruleForm.pass"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="checkPass">
        <el-input
          type="password"
          v-model="ruleForm.checkPass"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >提交</el-button
        >
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
/* 正则的验证 */
import { validateUser, validatePass, checkPwd } from '@/utils/validate.js'
/* 发送请求 */
import { editpwd, checkpwd } from '@/api/users.js'
import local from '../../utils/locl.js'
export default {
  data() {
    return {
      flag: false,
      ruleForm: {
        oldpass: '',
        pass: '',
        checkPass: ''
      },
      rules: {
        oldpass: [{ validator: validatePass, trigger: 'blur' }],
        pass: [{ validator: validatePass, trigger: 'blur' }],
        checkPass: [{ validator: checkPwd(this), trigger: 'blur' }]
      }
    }
  },
  methods: {
    /* 判断旧密码是否正确 */
    async judge() {
      if (this.ruleForm.oldpass !== '') {
        const { code, msg } = await checkpwd({
          oldPwd: this.ruleForm.oldpass
        })
        if (code === '00') {
          this.flag = true
        } else {
          this.flag = false
        }
      }
    },
    /* 修改密码 */
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          if (this.flag) {
            const { code, msg } = await editpwd({
              newPwd: this.ruleForm.pass
            })
            if (code === 0) {
              this.$router.push('/login')
              local.clear()
            }
          } else {
            this.$message({
              message: '不好意思，旧密码输入错误，不能修改',
              type: 'error'
            })
          }
        } else {
          this.$message({
            message: '格式错误',
            type: 'error'
          })
          return false
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-input {
  width: 178px;
}

/deep/.el-input__inne {
  width: 178px;
}
</style>
